/**
 * 手机端控制界面逻辑
 * 处理触控操作、工具切换、虚拟触控板等功能
 */

class MobileController {
    constructor() {
        this.currentTool = 'pen';
        this.currentMode = 'draw'; // 'draw' 或 'gallery'
        this.brushSize = 5;
        this.opacity = 100;
        this.isDrawing = false;
        this.lastPosition = null;
        this.trackpadActive = false;
        
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.setupVirtualTrackpad();
        this.setupToolButtons();
        this.setupModeButtons();
        this.setupGalleryFeatures();
        this.setupSliders();
        this.updateUI();
    }

    /**
     * 设置事件监听器
     */
    setupEventListeners() {
        // 连接按钮
        const connectBtn = document.getElementById('connect-btn');
        const disconnectBtn = document.getElementById('disconnect-btn');
        
        if (connectBtn) {
            connectBtn.addEventListener('click', () => this.connect());
        }
        
        if (disconnectBtn) {
            disconnectBtn.addEventListener('click', () => this.disconnect());
        }

        // 操作按钮
        const clearBtn = document.getElementById('clear-btn');
        const resetBtn = document.getElementById('reset-btn');
        const fullscreenBtn = document.getElementById('fullscreen-btn');
        const screenshotBtn = document.getElementById('screenshot-btn');
        const shareBtn = document.getElementById('share-btn');

        if (clearBtn) {
            clearBtn.addEventListener('click', () => this.clearCanvas());
        }
        
        if (resetBtn) {
            resetBtn.addEventListener('click', () => this.resetView());
        }
        
        if (fullscreenBtn) {
            fullscreenBtn.addEventListener('click', () => this.toggleFullscreen());
        }
        
        if (screenshotBtn) {
            screenshotBtn.addEventListener('click', () => this.takeScreenshot());
        }
        
        if (shareBtn) {
            shareBtn.addEventListener('click', () => this.shareLink());
        }

        // 监听WebSocket连接状态
        window.addEventListener('websocket-connected', () => {
            this.onConnected();
        });
        
        window.addEventListener('websocket-disconnected', () => {
            this.onDisconnected();
        });
        
        window.addEventListener('websocket-error', (event) => {
            this.onError(event.detail);
        });

        // 监听设备方向变化
        window.addEventListener('deviceOrientationChange', (event) => {
            this.handleOrientationChange(event.detail);
        });
    }

    /**
     * 设置虚拟触控板
     */
    setupVirtualTrackpad() {
        const trackpad = document.getElementById('virtual-trackpad');
        const cursor = document.getElementById('trackpad-cursor');
        
        if (!trackpad || !cursor) return;

        let startX, startY, currentX, currentY;
        let lastTouchDistance = 0;
        let lastTouchAngle = 0;
        let initialDistance = 0;
        let initialAngle = 0;
        
        // 计算两点间距离
        const getTouchDistance = (touch1, touch2) => {
            const dx = touch1.clientX - touch2.clientX;
            const dy = touch1.clientY - touch2.clientY;
            return Math.sqrt(dx * dx + dy * dy);
        };
        
        // 计算两点间角度（返回角度值）
        const getTouchAngle = (touch1, touch2) => {
            const radians = Math.atan2(touch2.clientY - touch1.clientY, touch2.clientX - touch1.clientX);
            return radians * 180 / Math.PI; // 转换为角度
        };
        
        // 触摸开始
        trackpad.addEventListener('touchstart', (e) => {
            e.preventDefault();
            this.trackpadActive = true;
            
            const rect = trackpad.getBoundingClientRect();
            
            if (e.touches.length === 1) {
                // 单指触控
                const touch = e.touches[0];
                startX = touch.clientX - rect.left;
                startY = touch.clientY - rect.top;
                currentX = startX;
                currentY = startY;
                
                cursor.style.left = startX + 'px';
                cursor.style.top = startY + 'px';
                cursor.style.display = 'block';
                
                this.sendTrackpadEvent('start', {
                    x: startX / rect.width,
                    y: startY / rect.height,
                    tool: this.currentTool,
                    brushSize: this.brushSize,
                    opacity: this.opacity / 100,
                    touchCount: 1
                });
            } else if (e.touches.length === 2) {
                // 双指触控
                const touch1 = e.touches[0];
                const touch2 = e.touches[1];
                
                initialDistance = getTouchDistance(touch1, touch2);
                lastTouchDistance = initialDistance;
                initialAngle = getTouchAngle(touch1, touch2);
                lastTouchAngle = initialAngle;
                
                // 计算中心点
                const centerX = (touch1.clientX + touch2.clientX) / 2 - rect.left;
                const centerY = (touch1.clientY + touch2.clientY) / 2 - rect.top;
                
                this.sendTrackpadEvent('multitouch_start', {
                    centerX: centerX / rect.width,
                    centerY: centerY / rect.height,
                    distance: initialDistance,
                    angle: initialAngle,
                    touchCount: 2
                });
            }
        });
        
        // 触摸移动
        trackpad.addEventListener('touchmove', (e) => {
            e.preventDefault();
            if (!this.trackpadActive) return;
            
            const rect = trackpad.getBoundingClientRect();
            
            if (e.touches.length === 1) {
                // 单指移动
                const touch = e.touches[0];
                currentX = Math.max(0, Math.min(rect.width, touch.clientX - rect.left));
                currentY = Math.max(0, Math.min(rect.height, touch.clientY - rect.top));
                
                cursor.style.left = currentX + 'px';
                cursor.style.top = currentY + 'px';
                
                this.sendTrackpadEvent('move', {
                    x: currentX / rect.width,
                    y: currentY / rect.height,
                    deltaX: (currentX - startX) / rect.width,
                    deltaY: (currentY - startY) / rect.height,
                    tool: this.currentTool,
                    brushSize: this.brushSize,
                    opacity: this.opacity / 100,
                    touchCount: 1
                });
                
                this.updateCoordinates(currentX, currentY);
            } else if (e.touches.length === 2) {
                // 双指移动 - 缩放和旋转
                const touch1 = e.touches[0];
                const touch2 = e.touches[1];
                
                const currentDistance = getTouchDistance(touch1, touch2);
                const currentAngle = getTouchAngle(touch1, touch2);
                
                // 计算缩放比例
                const scaleRatio = currentDistance / lastTouchDistance;
                const totalScale = currentDistance / initialDistance;
                
                // 计算旋转角度
                const rotationDelta = currentAngle - lastTouchAngle;
                const totalRotation = currentAngle - initialAngle;
                
                // 计算中心点
                const centerX = (touch1.clientX + touch2.clientX) / 2 - rect.left;
                const centerY = (touch1.clientY + touch2.clientY) / 2 - rect.top;
                
                this.sendTrackpadEvent('multitouch_move', {
                    centerX: centerX / rect.width,
                    centerY: centerY / rect.height,
                    scaleRatio: scaleRatio,
                    totalScale: totalScale,
                    rotationDelta: rotationDelta,
                    totalRotation: totalRotation,
                    distance: currentDistance,
                    angle: currentAngle,
                    touchCount: 2
                });
                
                lastTouchDistance = currentDistance;
                lastTouchAngle = currentAngle;
            }
        });
        
        // 触摸结束
        trackpad.addEventListener('touchend', (e) => {
            e.preventDefault();
            
            const rect = trackpad.getBoundingClientRect();
            
            if (e.touches.length === 0) {
                // 所有手指离开
                this.trackpadActive = false;
                
                this.sendTrackpadEvent('end', {
                    x: currentX / rect.width,
                    y: currentY / rect.height,
                    touchCount: 0
                });
                
                setTimeout(() => {
                    cursor.style.display = 'none';
                }, 500);
            } else if (e.touches.length === 1) {
                // 从双指变为单指
                const touch = e.touches[0];
                currentX = touch.clientX - rect.left;
                currentY = touch.clientY - rect.top;
                
                cursor.style.left = currentX + 'px';
                cursor.style.top = currentY + 'px';
                cursor.style.display = 'block';
                
                this.sendTrackpadEvent('multitouch_end', {
                    x: currentX / rect.width,
                    y: currentY / rect.height,
                    touchCount: 1
                });
            }
        });
        
        // 鼠标事件支持（用于调试）
        trackpad.addEventListener('mousedown', (e) => {
            e.preventDefault();
            this.trackpadActive = true;
            
            const rect = trackpad.getBoundingClientRect();
            currentX = e.clientX - rect.left;
            currentY = e.clientY - rect.top;
            
            cursor.style.left = currentX + 'px';
            cursor.style.top = currentY + 'px';
            cursor.style.display = 'block';
        });
        
        trackpad.addEventListener('mousemove', (e) => {
            if (!this.trackpadActive) return;
            
            const rect = trackpad.getBoundingClientRect();
            currentX = e.clientX - rect.left;
            currentY = e.clientY - rect.top;
            
            cursor.style.left = currentX + 'px';
            cursor.style.top = currentY + 'px';
            
            this.updateCoordinates(currentX, currentY);
        });
        
        trackpad.addEventListener('mouseup', () => {
            this.trackpadActive = false;
            setTimeout(() => {
                cursor.style.display = 'none';
            }, 500);
        });
    }

    /**
     * 设置工具按钮
     */
    setupToolButtons() {
        const toolButtons = document.querySelectorAll('.tool-button');
        
        toolButtons.forEach(button => {
            button.addEventListener('click', () => {
                const tool = button.dataset.tool;
                this.selectTool(tool);
            });
        });
    }

    /**
     * 设置模式切换按钮
     */
    setupModeButtons() {
        const modeButtons = document.querySelectorAll('.mode-button');
        
        modeButtons.forEach(button => {
            button.addEventListener('click', () => {
                const mode = button.dataset.mode;
                this.switchMode(mode);
            });
        });
    }

    /**
     * 设置画册功能
     */
    setupGalleryFeatures() {
        // 选择图片按钮
        const selectImageBtn = document.getElementById('select-image-btn');
        const imageInput = document.getElementById('image-input');
        
        if (selectImageBtn && imageInput) {
            selectImageBtn.addEventListener('click', () => {
                imageInput.click();
            });
            
            imageInput.addEventListener('change', (e) => {
                this.handleImageSelection(e);
            });
        }
        
        // 拍照按钮
        const takePhotoBtn = document.getElementById('take-photo-btn');
        if (takePhotoBtn) {
            takePhotoBtn.addEventListener('click', () => {
                this.takePhoto();
            });
        }
        
        // 清空画册按钮
        const clearGalleryBtn = document.getElementById('clear-gallery-btn');
        if (clearGalleryBtn) {
            clearGalleryBtn.addEventListener('click', () => {
                this.clearGallery();
            });
        }
        
        // 上一张图片按钮
        const prevImageBtn = document.getElementById('prev-image-btn');
        if (prevImageBtn) {
            prevImageBtn.addEventListener('click', () => {
                this.previousImage();
            });
        }
        
        // 下一张图片按钮
        const nextImageBtn = document.getElementById('next-image-btn');
        if (nextImageBtn) {
            nextImageBtn.addEventListener('click', () => {
                this.nextImage();
            });
        }
    }

    /**
     * 设置滑块控件
     */
    setupSliders() {
        const brushSizeSlider = document.getElementById('brush-size');
        const opacitySlider = document.getElementById('opacity');
        
        if (brushSizeSlider) {
            brushSizeSlider.addEventListener('input', (e) => {
                this.brushSize = parseInt(e.target.value);
                document.getElementById('brush-size-value').textContent = this.brushSize;
                this.sendSettingsUpdate();
            });
        }
        
        if (opacitySlider) {
            opacitySlider.addEventListener('input', (e) => {
                this.opacity = parseInt(e.target.value);
                document.getElementById('opacity-value').textContent = this.opacity + '%';
                this.sendSettingsUpdate();
            });
        }
    }

    /**
     * 选择工具
     */
    selectTool(tool) {
        this.currentTool = tool;
        
        // 更新按钮状态
        document.querySelectorAll('.tool-button').forEach(btn => {
            btn.classList.remove('active');
        });
        
        const activeButton = document.querySelector(`[data-tool="${tool}"]`);
        if (activeButton) {
            activeButton.classList.add('active');
        }
        
        // 更新工具显示
        const toolNames = {
            pen: '画笔',
            eraser: '橡皮擦',
            building: '建筑',
            tree: '树木',
            road: '道路',
            water: '水域'
        };
        
        const currentToolElement = document.getElementById('current-tool');
        if (currentToolElement) {
            currentToolElement.textContent = toolNames[tool] || tool;
        }
        
        this.sendToolChange();
    }

    /**
     * 发送触控板事件
     */
    sendTrackpadEvent(type, data) {
        if (window.websocketManager && window.websocketManager.isConnected()) {
            let eventType;
            
            // 多指触控事件使用专门的消息类型
            if (type === 'multitouch_start' || type === 'multitouch_move' || type === 'multitouch_end') {
                eventType = type; // 直接使用多指触控事件类型
            } else {
                // 其他事件根据模式选择类型
                eventType = this.currentMode === 'gallery' ? 'gallery_gesture' : 'trackpad_event';
            }
            
            window.websocketManager.send({
                type: eventType,
                event: type,
                data: data,
                mode: this.currentMode,
                timestamp: Date.now(),
                source: 'mobile_controller'
            });
        }
    }

    /**
     * 发送工具变更
     */
    sendToolChange() {
        if (window.websocketManager && window.websocketManager.isConnected()) {
            window.websocketManager.send({
                type: 'tool_change',
                tool: this.currentTool,
                timestamp: Date.now(),
                source: 'mobile_controller'
            });
        }
    }

    /**
     * 切换操作模式
     */
    switchMode(mode) {
        this.currentMode = mode;
        
        // 更新按钮状态
        document.querySelectorAll('.mode-button').forEach(btn => {
            btn.classList.remove('active');
        });
        
        const activeButton = document.querySelector(`[data-mode="${mode}"]`);
        if (activeButton) {
            activeButton.classList.add('active');
        }
        
        // 切换界面显示
        const drawToolsSection = document.getElementById('draw-tools-section');
        const galleryToolsSection = document.getElementById('gallery-tools-section');
        
        if (mode === 'draw') {
            drawToolsSection.style.display = 'block';
            galleryToolsSection.style.display = 'none';
            this.updateActionType('画笔模式');
        } else if (mode === 'gallery') {
            drawToolsSection.style.display = 'none';
            galleryToolsSection.style.display = 'block';
            this.updateActionType('画册模式');
        }
        
        // 发送模式切换消息
        this.sendModeChange();
    }

    /**
     * 发送模式切换消息
     */
    sendModeChange() {
        if (window.websocketManager && window.websocketManager.isConnected()) {
            window.websocketManager.send({
                type: 'mode_change',
                mode: this.currentMode,
                timestamp: Date.now(),
                source: 'mobile_controller'
            });
        }
    }

    /**
     * 处理图片选择
     */
    handleImageSelection(event) {
        const files = event.target.files;
        if (files.length === 0) return;
        
        Array.from(files).forEach(file => {
            if (file.type.startsWith('image/')) {
                this.processAndSendImage(file);
            }
        });
        
        // 清空input以允许重复选择同一文件
        event.target.value = '';
    }

    /**
     * 处理和发送图片
     */
    processAndSendImage(file) {
        const reader = new FileReader();
        
        reader.onload = (e) => {
            const imageData = e.target.result;
            
            // 创建图片元素获取尺寸信息
            const img = new Image();
            img.onload = () => {
                const imageInfo = {
                    type: 'image_share',
                    data: imageData,
                    filename: file.name,
                    size: file.size,
                    width: img.width,
                    height: img.height,
                    timestamp: Date.now(),
                    source: 'mobile_controller'
                };
                
                this.sendImageData(imageInfo);
                this.updateActionType(`分享图片: ${file.name}`);
            };
            
            img.src = imageData;
        };
        
        reader.readAsDataURL(file);
    }

    /**
     * 发送图片数据
     */
    sendImageData(imageInfo) {
        if (window.websocketManager && window.websocketManager.isConnected()) {
            window.websocketManager.send(imageInfo);
        } else {
            this.showToast('未连接到服务器，无法分享图片');
        }
    }

    /**
     * 拍照功能
     */
    takePhoto() {
        // 检查是否支持摄像头
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
            this.showToast('设备不支持摄像头功能');
            return;
        }
        
        navigator.mediaDevices.getUserMedia({ video: true })
            .then(stream => {
                this.openCameraModal(stream);
            })
            .catch(error => {
                console.error('摄像头访问失败:', error);
                this.showToast('无法访问摄像头');
            });
    }

    /**
     * 打开摄像头模态框
     */
    openCameraModal(stream) {
        // 创建摄像头界面
        const modal = document.createElement('div');
        modal.className = 'camera-modal';
        modal.innerHTML = `
            <div class="camera-container">
                <video id="camera-video" autoplay playsinline></video>
                <canvas id="camera-canvas" style="display: none;"></canvas>
                <div class="camera-controls">
                    <button id="capture-btn" class="control-button primary">📷 拍照</button>
                    <button id="close-camera-btn" class="control-button">❌ 关闭</button>
                </div>
            </div>
        `;
        
        // 添加样式
        const style = document.createElement('style');
        style.textContent = `
            .camera-modal {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.9);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 10000;
            }
            .camera-container {
                background: white;
                border-radius: 15px;
                padding: 20px;
                max-width: 90vw;
                max-height: 90vh;
                display: flex;
                flex-direction: column;
                align-items: center;
            }
            #camera-video {
                width: 100%;
                max-width: 400px;
                border-radius: 10px;
                margin-bottom: 15px;
            }
            .camera-controls {
                display: flex;
                gap: 10px;
            }
        `;
        
        document.head.appendChild(style);
        document.body.appendChild(modal);
        
        const video = modal.querySelector('#camera-video');
        const canvas = modal.querySelector('#camera-canvas');
        const captureBtn = modal.querySelector('#capture-btn');
        const closeBtn = modal.querySelector('#close-camera-btn');
        
        video.srcObject = stream;
        
        // 拍照按钮事件
        captureBtn.addEventListener('click', () => {
            this.capturePhoto(video, canvas, stream);
            document.body.removeChild(modal);
            document.head.removeChild(style);
        });
        
        // 关闭按钮事件
        closeBtn.addEventListener('click', () => {
            stream.getTracks().forEach(track => track.stop());
            document.body.removeChild(modal);
            document.head.removeChild(style);
        });
    }

    /**
     * 拍照并处理
     */
    capturePhoto(video, canvas, stream) {
        const context = canvas.getContext('2d');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        
        context.drawImage(video, 0, 0);
        
        // 停止摄像头
        stream.getTracks().forEach(track => track.stop());
        
        // 转换为blob并发送
        canvas.toBlob(blob => {
            const file = new File([blob], `photo_${Date.now()}.jpg`, { type: 'image/jpeg' });
            this.processAndSendImage(file);
        }, 'image/jpeg', 0.8);
    }

    /**
     * 清空画册
     */
    clearGallery() {
        if (window.websocketManager && window.websocketManager.isConnected()) {
            window.websocketManager.send({
                type: 'clear_gallery',
                timestamp: Date.now(),
                source: 'mobile_controller'
            });
            
            this.updateActionType('清空画册');
        }
    }
    
    /**
     * 切换到上一张图片
     */
    previousImage() {
        if (window.websocketManager && window.websocketManager.isConnected()) {
            window.websocketManager.send({
                type: 'gallery_navigate',
                action: 'previous',
                timestamp: Date.now(),
                source: 'mobile_controller'
            });
            
            this.updateActionType('上一张图片');
        }
    }
    
    /**
     * 切换到下一张图片
     */
    nextImage() {
        if (window.websocketManager && window.websocketManager.isConnected()) {
            window.websocketManager.send({
                type: 'gallery_navigate',
                action: 'next',
                timestamp: Date.now(),
                source: 'mobile_controller'
            });
            
            this.updateActionType('下一张图片');
        }
    }

    /**
     * 发送设置更新
     */
    sendSettingsUpdate() {
        if (window.websocketManager && window.websocketManager.isConnected()) {
            window.websocketManager.send({
                type: 'settings_update',
                settings: {
                    brushSize: this.brushSize,
                    opacity: this.opacity / 100,
                    tool: this.currentTool
                },
                timestamp: Date.now(),
                source: 'mobile_controller'
            });
        }
    }

    /**
     * 连接服务器
     */
    connect() {
        if (window.websocketManager) {
            window.websocketManager.connect();
        }
    }

    /**
     * 断开连接
     */
    disconnect() {
        if (window.websocketManager) {
            window.websocketManager.disconnect();
        }
    }

    /**
     * 清空画布
     */
    clearCanvas() {
        if (window.websocketManager && window.websocketManager.isConnected()) {
            window.websocketManager.send({
                type: 'clear_canvas',
                timestamp: Date.now(),
                source: 'mobile_controller'
            });
        }
        
        this.updateActionType('清空画布');
    }

    /**
     * 重置视图
     */
    resetView() {
        if (window.websocketManager && window.websocketManager.isConnected()) {
            window.websocketManager.send({
                type: 'reset_view',
                timestamp: Date.now(),
                source: 'mobile_controller'
            });
        }
        
        this.updateActionType('重置视图');
    }

    /**
     * 切换全屏
     */
    toggleFullscreen() {
        if (!document.fullscreenElement) {
            document.documentElement.requestFullscreen();
        } else {
            document.exitFullscreen();
        }
    }

    /**
     * 截图
     */
    takeScreenshot() {
        if (window.websocketManager && window.websocketManager.isConnected()) {
            window.websocketManager.send({
                type: 'take_screenshot',
                timestamp: Date.now(),
                source: 'mobile_controller'
            });
        }
        
        this.updateActionType('截图保存');
    }

    /**
     * 分享链接
     */
    shareLink() {
        const url = window.location.origin + window.location.pathname.replace('mobile-control.html', 'display-screen.html');
        
        if (navigator.share) {
            navigator.share({
                title: '沙盘显示屏',
                text: '在大屏设备上打开此链接查看沙盘',
                url: url
            });
        } else {
            // 复制到剪贴板
            navigator.clipboard.writeText(url).then(() => {
                this.showToast('显示屏链接已复制到剪贴板');
            });
        }
    }

    /**
     * 更新坐标显示
     */
    updateCoordinates(x, y) {
        const coordX = document.getElementById('coord-x');
        const coordY = document.getElementById('coord-y');
        
        if (coordX) coordX.textContent = Math.round(x);
        if (coordY) coordY.textContent = Math.round(y);
    }

    /**
     * 更新操作类型显示
     */
    updateActionType(action) {
        const actionElement = document.getElementById('action-type');
        if (actionElement) {
            actionElement.textContent = action;
            
            // 3秒后恢复为待命状态
            setTimeout(() => {
                actionElement.textContent = '待命';
            }, 3000);
        }
    }

    /**
     * 连接成功回调
     */
    onConnected() {
        const statusIndicator = document.getElementById('status-indicator');
        const statusText = document.getElementById('status-text');
        const connectBtn = document.getElementById('connect-btn');
        const disconnectBtn = document.getElementById('disconnect-btn');
        
        if (statusIndicator) statusIndicator.classList.add('connected');
        if (statusText) statusText.textContent = '已连接';
        if (connectBtn) connectBtn.disabled = true;
        if (disconnectBtn) disconnectBtn.disabled = false;
        
        this.showToast('已连接到服务器');
        this.updateActionType('连接成功');
    }

    /**
     * 断开连接回调
     */
    onDisconnected() {
        const statusIndicator = document.getElementById('status-indicator');
        const statusText = document.getElementById('status-text');
        const connectBtn = document.getElementById('connect-btn');
        const disconnectBtn = document.getElementById('disconnect-btn');
        
        if (statusIndicator) statusIndicator.classList.remove('connected');
        if (statusText) statusText.textContent = '未连接';
        if (connectBtn) connectBtn.disabled = false;
        if (disconnectBtn) disconnectBtn.disabled = true;
        
        this.showToast('已断开连接');
        this.updateActionType('连接断开');
    }

    /**
     * 错误回调
     */
    onError(error) {
        this.showToast('连接错误: ' + error.message);
        this.updateActionType('连接错误');
    }

    /**
     * 处理设备方向变化
     */
    handleOrientationChange(detail) {
        // 可以根据方向变化调整界面布局
        console.log('设备方向变化:', detail.orientation);
    }

    /**
     * 显示提示消息
     */
    showToast(message) {
        // 创建简单的toast提示
        const toast = document.createElement('div');
        toast.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 15px 25px;
            border-radius: 25px;
            z-index: 10000;
            font-size: 16px;
            text-align: center;
        `;
        toast.textContent = message;
        
        document.body.appendChild(toast);
        
        setTimeout(() => {
            toast.remove();
        }, 3000);
    }

    /**
     * 更新UI状态
     */
    updateUI() {
        // 初始化UI状态
        this.selectTool(this.currentTool);
        
        const brushSizeValue = document.getElementById('brush-size-value');
        const opacityValue = document.getElementById('opacity-value');
        
        if (brushSizeValue) brushSizeValue.textContent = this.brushSize;
        if (opacityValue) opacityValue.textContent = this.opacity + '%';
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    window.mobileController = new MobileController();
});

// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = MobileController;
}